#!/usr/bin/env python3
"""
Prometheus告警分析配置模块
支持多种环境配置和API密钥管理
"""

import os
import logging
from dotenv import load_dotenv
from typing import Dict, Any

# 加载环境变量
load_dotenv()

logger = logging.getLogger(__name__)

class Config:
    """配置管理类 - 支持Prometheus API和通知配置"""
    
    @staticmethod
    def get_prometheus_config() -> Dict[str, Any]:
        """获取Prometheus API配置"""
        return {
            'prometheus_url': os.getenv('PROMETHEUS_URL', 'http://localhost:9090'),
            'query_timeout': int(os.getenv('PROMETHEUS_QUERY_TIMEOUT', '30')),
            'max_alerts': int(os.getenv('PROMETHEUS_MAX_ALERTS', '100')),
        }
    
    @staticmethod
    def get_api_config() -> Dict[str, Any]:
        """获取AI分析API配置"""
        ai_engine = os.getenv('AI_ENGINE', 'deepseek').lower()
        
        config = {
            'ai_engine': ai_engine,
            'enable_ai_analysis': os.getenv('ENABLE_AI_ANALYSIS', 'true').lower() == 'true',
            'deepseek': {
                'api_key': os.getenv('DEEPSEEK_API_KEY', ''),
                'api_url': os.getenv('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1/chat/completions'),
                'model': os.getenv('DEEPSEEK_MODEL', 'deepseek-chat'),
                'timeout': int(os.getenv('DEEPSEEK_TIMEOUT', '30')),
                'enabled': ai_engine == 'deepseek'
            },
            'ollama': {
                'base_url': os.getenv('OLLAMA_BASE_URL', 'http://localhost:11434'),
                'model': os.getenv('OLLAMA_MODEL', 'llama3.1:8b'),
                'timeout': int(os.getenv('OLLAMA_TIMEOUT', '60')),
                'enabled': ai_engine == 'ollama'
            }
        }
        
        return config
    
    @staticmethod
    def get_notification_config() -> Dict[str, Any]:
        """获取通知配置"""
        return {
            'feishu_webhook': os.getenv('FEISHU_WEBHOOK_URL', ''),
            'enable_notification': os.getenv('ENABLE_NOTIFICATION', 'true').lower() == 'true',
            'notification_level': os.getenv('NOTIFICATION_LEVEL', 'warning'),  # info, warning, critical
        }
    
    @staticmethod
    def get_logging_config() -> Dict[str, Any]:
        """获取日志配置"""
        return {
            'log_level': os.getenv('LOG_LEVEL', 'INFO'),
            'log_file': os.getenv('LOG_FILE', 'prometheus_analyzer.log'),
            'log_format': os.getenv('LOG_FORMAT', '%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
        }
    
    @staticmethod
    def setup_logging():
        """设置日志配置"""
        log_config = Config.get_logging_config()
        
        logging.basicConfig(
            level=getattr(logging, log_config['log_level']),
            format=log_config['log_format'],
            handlers=[
                logging.FileHandler(log_config['log_file']),
                logging.StreamHandler()
            ]
        )
        
        logger.info("日志系统初始化完成")
    
    @staticmethod
    def validate_config() -> bool:
        """验证配置完整性"""
        prometheus_config = Config.get_prometheus_config()
        api_config = Config.get_api_config()
        
        # 检查Prometheus URL
        if not prometheus_config['prometheus_url']:
            logger.error("未配置Prometheus URL")
            return False
        
        # 检查AI引擎配置
        ai_engine = api_config['ai_engine']
        if ai_engine not in ['deepseek', 'ollama']:
            logger.error(f"AI引擎配置无效: {ai_engine} (仅支持 deepseek 或 ollama)")
            return False
            
        # 根据选择的引擎验证相应配置
        if api_config['enable_ai_analysis']:
            if ai_engine == 'deepseek' and not api_config['deepseek']['api_key']:
                logger.warning("未配置DeepSeek API密钥，将使用内置分析")
            elif ai_engine == 'ollama' and not api_config['ollama']['base_url']:
                logger.warning("未配置Ollama服务地址，将使用内置分析")
        
        logger.info(f"配置验证通过，当前AI引擎: {ai_engine}")
        return True